package com.copote.pdfutils.common;

import com.copote.common.FileCopyUtils;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;

/**
 * @ClassName: PDFFonts
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: 湖南湘邮科技股份有限公司/RedStar
 * @date: 2023/10/12 13:10
 * @Copyright: 2019 2000 - 2022 HuNan Copote Science & Technology CO., LTD. All Rights Reserved.<br/>
 * 注意：本内容仅限于湖南湘邮科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
@Slf4j
public class PDFFonts {
    /**
     * 获取中文字体
     *
     * @return 返回 中文PdfFont 字体
     * @throws IOException
     */

    public static PdfFont getPDFFont() throws IOException {
        boolean isSysFont = true;
        PdfFont font;
        if (isSysFont) {
            //中文字体
            font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H");
        } else {
            String FONT = GetFontFile();
            //Fonts need to be embedded
            font = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED);
        }
        return font;
    }

    /**
     * 获取生成自定义PDF所需的字体路径<br/>
     * 使用自定义字库时，需要把pdfutils/resources/simsun.ttc字库拷贝到资源目录中
     *
     * @return
     * @throws IOException
     */
    public static String GetFontFile() throws IOException {
        String locationPath = ResourceUtils.getURL("classpath:").getPath();//classes目录
        String FontName = "simsun.ttc";
        String Font = FontName + ",1";//"msyh.ttc,1";

        String retStr = locationPath + Font;
        ApplicationHome ah = new ApplicationHome(PDFFonts.class);
        String rootdir = ah.getSource().getParent();//jar所在目录
        if (locationPath.contains("!")) {
            File file = new File(rootdir + "/" + FontName);
            if (!file.exists()) {
                FileCopyUtils.copy(FontName);
            }
            retStr = rootdir + Font;
        }
        log.info("Font:{}", retStr);
        return retStr;
    }

}
